﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using Newtonsoft.Json;
using Power.Common;
using Power.Models;
using Power.View;
using Power.View.Dialog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Power.ViewModel
{
    public class AIReviewDetailViewModel : ViewModelBase
    {
        /// <summary>
        /// 图片地址
        /// </summary>
        public static string imgSrc = "/Resources/images/";

        private AIReviewDetail model;

        public int blockFlag;

        public VarRectangle varRectangle;
        public List<DataList> Datalist;
        public AIReviewDetailViewModel(AIReviewDetail model)
        {
            this.model = model;
            this.model.datagrid.SelectedCellsChanged += datagrid_SelectedCellsChanged;
            this.model.selLeft.SelectionChanged += SelLeft_SelectionChanged;
            Return = new RelayCommand(OnReturn);
            Delete = new RelayCommand(OnDelete);
            Up = new RelayCommand(OnUp);
            Down = new RelayCommand(OnDown);
            Grade = new RelayCommand(OnGrade);
            PositionCorrection = new RelayCommand(OnPositionCorrection);
            //来源excel
            Datalist = GetDataListList(this.model.workSpaceEntity.Id);
            Data = new AIReviewDetailEntity
            {
                //初始加载的图片列表
                DataListList = new ObservableCollection<DataList>(Datalist),
                //原缺陷类别
                CategorySelectListLeft = Common.Common.GetDefectNameSelectList(),
                //原缺陷类别
                CategorySelectListDown = Common.Common.GetDefectCategorySelectList(),
                //原缺陷等级
                LevelSelectList = Common.Common.GetDefectLevel1SelectList(),
                //AI识别缺陷类别
                AICategorySelectList = Common.Common.GetDefectCategorySelectList(),
                //AI识别缺陷等级
                AILevelSelectList = Common.Common.GetDefectLevel1SelectList(),
            };
            if (this.model.fromID == "-1") {
                //默认选中第一个缺陷
                this.model.datagrid.SelectedIndex = 0;
                return;
            }
            var curItem = Datalist.FirstOrDefault(a => a.Id == this.model.fromID);
            if (curItem == null) {
                this.model.datagrid.SelectedIndex = 0;
                return;
            }
            int index = Datalist.IndexOf(curItem);
            if (index >= 0)
            {
                this.model.datagrid.SelectedIndex = index;
            }
            else {
                this.model.datagrid.SelectedIndex = 0;
            }
        }

        private void SelLeft_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var ck = sender as CheckComboBox;
            if (ck.SelectedItems.Count > 0)
            {
                List<string> list = new List<string>();
                foreach (SelectListItem item in ck.SelectedItems)
                {
                    list.Add(item.SelectID);
                }
                this.Data.DataListList = new ObservableCollection<DataList>(Datalist.Where(a => list.Contains(a.PriDefect.Code)));
            }
            else
            {
                this.Data.DataListList = new ObservableCollection<DataList>(Datalist);
            }
        }

        public void OnBlockClick(Button obj)
        {
            blockFlag = Convert.ToInt32(obj.Tag);
            //获取弹层所有按钮
            List<Button> btnList = Common.Common.GetChildObjects<Button>((Grid)obj.Parent, 0);
            btnList.ForEach((item) =>
            {
                Border border = Common.Common.GetVisualChild<Border>(item);
                //移除border边框选中效果
                border.BorderBrush = new SolidColorBrush(Color.FromRgb(241, 241, 241));
                border.BorderThickness = new Thickness(0, 0, 3, 3);
            });
            Border curBorder = Common.Common.GetVisualChild<Border>(obj);
            //设置当前border边框效果
            curBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(106, 165, 207));
            curBorder.BorderThickness = new Thickness(3, 3, 3, 3);
        }

        private void OnPositionCorrection()
        {
            //空数据
            if (Data.DataListList == null || Data.DataListList.Count < 1) {
                return;
            }
            if (varRectangle == null)
            {
                var item = Data.DataListList.Single(p => p.Id == this.Data.DataListItem.Id);
                varRectangle = new VarRectangle(this.model.canvas, item.Position);
            }
            if (varRectangle != null)
            {
                if (varRectangle.IsChange)
                {
                    varRectangle.UnBindEvent();
                }
                else
                {

                    varRectangle.BindEvent();
                }
            }
        }

        private void OnGrade()
        {
            if (varRectangle == null)
            {
                MessagePrompt msg = new MessagePrompt($"未找到缺陷位置");
                msg.ShowDialog();
                return;
            }
            //获取坐标
            var postion = varRectangle.GetPostion();

            if (this.Data.CurDataListItem == null) {
                return;
            }
            byte[] imageBytes = null;
            List<PicturesInfo> picList = StaticCache.AiDicPic[model.workSpaceEntity.Id];
            if (picList == null || picList.Count < 1)
            {
                if (!File.Exists(this.Data.CurDataListItem.ImagesSrc))
                {
                    MessagePrompt msg = new MessagePrompt($"未能找到，序号{this.Data.CurDataListItem.Id}的检查图片，请确认路径图片名称是否正确");
                    msg.ShowDialog();
                    return;
                }
                imageBytes = Common.Common.GetImagesBytes(this.Data.CurDataListItem.ImagesSrc);
            }
            else {
                imageBytes = picList.ElementAtOrDefault(this.Data.DataListList.IndexOf(this.Data.CurDataListItem))?.PictureData;
            }
            //调用接口获取ai识别结果
            string result = DistinguishReulst(imageBytes, postion);
            this.Data.DataListItem.AIDefect = JsonConvert.DeserializeObject<DefectEntity>(result);
        }

        /// <summary>
        /// 下一条
        /// </summary>
        private void OnDown()
        {

            if (this.Data.DataListItem == null || string.IsNullOrWhiteSpace(this.Data.DataListItem.Id))
            {
                return;
            }
            var model = this.Data.CurDataListItem;
            var index = this.Data.DataListList.IndexOf(model);
            //SaveChange();
            if (index < this.Data.DataListList.Count - 1)
            {
                //设置左侧选中下一条
                this.model.datagrid.SelectedIndex = index + 1;
            }
        }

        /// <summary>
        /// 上一条
        /// </summary>
        private void OnUp()
        {
            if (this.Data.DataListItem == null || string.IsNullOrWhiteSpace(this.Data.DataListItem.Id))
            {
                return;
            }
            var model = this.Data.CurDataListItem;
            var index = this.Data.DataListList.IndexOf(model);
            //判断数据是否变化
            //SaveChange();
            if (index > 0)
            {
                //设置左侧选中上一条
                this.model.datagrid.SelectedIndex = index - 1;
            }
        }

        private void datagrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            SaveChange();

            List<PicturesInfo> picList = StaticCache.AiDicPic[model.workSpaceEntity.Id];
            //设置缺陷详情
            if (e.AddedCells.Count == 0)
            {
                this.Data.CurDataListItem = Data.DataListList.FirstOrDefault();
                //绑定图片
                if (picList != null && picList.Count > 0)
                {
                    this.model.image.ImageSource = ByteArrayToBitmapImage(picList.FirstOrDefault()?.PictureData);
                }
                else {
                    //防止空数据报错
                    if (!string.IsNullOrWhiteSpace(this.Data.CurDataListItem?.ImagesSrc)) { 
                        this.model.image.ImageSource = new BitmapImage(new Uri(this.Data.CurDataListItem.ImagesSrc, UriKind.Relative));
                    }
                }
            }
            else
            {
                this.Data.CurDataListItem = (DataList)e.AddedCells[0].Item;
                int index = this.Data.DataListList.IndexOf(this.Data.CurDataListItem);
                //绑定图片
                if (picList != null && picList.Count > 0)
                {
                    this.model.image.ImageSource = ByteArrayToBitmapImage(picList.ElementAtOrDefault(index).PictureData);
                }
                else {
                    this.model.image.ImageSource = new BitmapImage(new Uri(this.Data.CurDataListItem.ImagesSrc, UriKind.Relative));
                }
            }
            this.Data.DataListItem = JsonConvert.DeserializeObject<DataList>(JsonConvert.SerializeObject(Data.CurDataListItem));
            if (Data.DataListItem == null) {//处理数据全部删除
                Data.DataListItem = new DataList(); 
            }
            if (this.Data.DataListItem.AIDefect == null) {
                this.Data.DataListItem.AIDefect = new DefectEntity();
            }

            this.model.canvas.Children.Clear();
            varRectangle = null;
        }

        /// <summary>
        /// 解析字节数组成图片
        /// </summary>
        /// <param name="byteArray"></param>
        /// <returns></returns>
        public BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
        {
            BitmapImage bmp = null;
            try
            {
                bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(byteArray);
                bmp.EndInit();
            }
            catch
            {
                bmp = null;
            }
            return bmp;
        }

        /// <summary>
        /// 初始化数据，防止空值
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public List<DataList> GetDataListList(string Id) {
            List<DataList> list = new List<DataList>();
            list = StaticCache.AiDic[Id];
            foreach (var item in list)
            {
                if(item.PriDefect.CircleDirection == null)
                    item.PriDefect.CircleDirection = "";
            }
            return list;
        }
        private void OnDelete()
        {
            if (this.Data.DataListItem == null || string.IsNullOrWhiteSpace(this.Data.DataListItem.Id)) {
                return;
            }
            if (string.IsNullOrWhiteSpace(this.Data.DataListItem.ImagesName))
            {
                MessagePrompt box2 = new MessagePrompt("未查询到检查图片，无法删除数据");
                box2.ShowDialog();
                return;
            }

            MessagePrompt box = new MessagePrompt("是否删除该数据？", true);
            if (box.ShowDialog() == true) {
                List<PicturesInfo> picList = StaticCache.AiDicPic[model.workSpaceEntity.Id];
                var result = ExcelHelper.DeleteExcelRow(this.model.workSpaceEntity.LocalFile, this.Data.DataListItem.ImagesName,
                    picList == null || picList.Count < 1 ? -1 : Convert.ToInt32(this.Data.CurDataListItem.Id));

                if (!result.Success) {
                    MessagePrompt box2 = new MessagePrompt($"删除失败:{result.Message}");
                    box2.ShowDialog();
                    return;
                }
                var index = this.Data.DataListList.IndexOf(this.Data.CurDataListItem);
                //处理缓存中的数据
                Datalist.Remove(this.Data.CurDataListItem);
                if (picList != null && picList.Count > 0)
                {
                    picList.RemoveAt(index);
                }
                //移动选中到下一行
                this.Data.DataListList = new ObservableCollection<DataList>(Datalist);
                if (index < this.Data.DataListList.Count)
                {
                    //设置左侧选中下一条
                    this.model.datagrid.SelectedIndex = index;
                }
                else {
                    if (Datalist.Count == 0)
                    {
                        this.model.datagrid.SelectedIndex = -1;
                    }
                    else {
                        this.model.datagrid.SelectedIndex = 0;
                    }
                }
            }
        }

        private void OnReturn()
        {
            AIReview aIReview = this.model.aiReview;
            var window = System.Windows.Window.GetWindow(this.model);
            if (aIReview == null) {
                aIReview = new AIReview();
            }
            aIReview.Context.Data.DataListList = new ObservableCollection<DataList>(Datalist);
            ((window as MainWindow).DataContext as MainViewModel).UserContent = aIReview;
        }

        private void SaveChange(bool checkRectangle = true)
        {
            if ((blockFlag == 2 && this.Data.DataListItem.AIDefect.IsChanged(this.Data.CurDataListItem.AIDefect ?? new DefectEntity())) || (varRectangle != null && checkRectangle))
            {
                if (varRectangle == null)
                {
                    MessagePrompt msg = new MessagePrompt($"未找到缺陷位置");
                    msg.ShowDialog();
                    return;
                }

                MessagePrompt box = new MessagePrompt("存在未保存的修改，是否保存？", true);
                var flag = box.ShowDialog();
                if (flag == true)
                {
                    List<PicturesInfo> picList = StaticCache.AiDicPic[this.model.workSpaceEntity.Id];
                    var result = ExcelHelper.WriteExcelRow(this.model.workSpaceEntity.LocalFile, this.Data.DataListItem.ImagesName, Data.DataListItem.AIDefect,
                        varRectangle.GetPostion(), picList == null || picList.Count < 1 ? -1 : Convert.ToInt32(this.Data.CurDataListItem.Id));
                    if (!result.Success)
                    {
                        MessagePrompt box2 = new MessagePrompt($"更新失败:{result.Message}");
                        box2.ShowDialog();
                        return;
                    }
                    this.Data.CurDataListItem.AIDefect = Data.DataListItem.AIDefect;
                    var item = Data.DataListList.Single(p => p.Id == this.Data.DataListItem.Id);
                    item.Position = varRectangle.GetPostion();
                }
            }
        }

        private string DistinguishReulst(byte[] imageBytes, string postion)
        {
            //imageStr图片二进制字符串  postion位置信息
            return "{\"Code\":\"QF\",\"Level\":2,\"Type\":\"结构性\",\"Name\":\"起伏\",\"CircleDirection\":\"0910\",\"Describe\":\"描述\"}";
        }

        #region Command
        public RelayCommand Return {  get; private set; }
        public RelayCommand Delete { get; private set; }
        public RelayCommand Up { get; private set; }
        public RelayCommand Down { get; private set; }
        public RelayCommand PositionCorrection {  get; private set; }
        public RelayCommand Grade {  get; private set; }
        #endregion

        #region 数据绑定
        public AIReviewDetailEntity Data { get; private set; }
        #endregion
    }
}
